package com.birboot.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//响应对象
public class HttpServletResponse {
    private Socket socket;
    //状态行相关信息
    private int a = 200;//状态代码
    private String str1 = "OK";//状态描述

    //响应头相关信息
    private File contentFile;//响应正文对应的实体文件

    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }

        //向客户端发送一行字符串
    public void response() throws IOException{
        //3.1发送状态行
        sendStatusLine();

        //3.2发送响应头
        sendHeaders();

        //3.3发送响应正文
        sendContent();
    }

    //发送状态行
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1" + " " + a + " " + str1);
    }

    //发送响应头
    private void sendHeaders() throws IOException {
        println("Content-Type: text/html");
        println("Content-Length: " + contentFile.length());
        println("");
    }

    //发送响应正文
    private void sendContent() throws IOException {
        FileInputStream fis = new FileInputStream(contentFile);
        OutputStream out = socket.getOutputStream();
        byte[] buf = new byte[1024 * 10];
        int a;
        while ((a = fis.read(buf)) != -1) {
            out.write(buf, 0, a);
        }
    }

        private void println(String line) throws IOException {
            OutputStream out = socket.getOutputStream();
            byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
            out.write(data);
            out.write(13);//回车
            out.write(10);//换行
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public String getStr1() {
        return str1;
    }

    public void setStr1(String str1) {
        this.str1 = str1;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }

}
